package com.soker.user.controller;

import com.soker.fan.pojo.Fan;
import com.soker.page.Page;
import com.soker.page.PageConstants;
import com.soker.user.pojo.History;
import com.soker.user.pojo.User;
import com.soker.user.service.UserService;
import com.soker.video.pojo.Video;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    //验证密码
    @RequestMapping("/verifyPasswordByUsername")
    public String verifyPasswordByUsername(String username, String password, HttpSession session, Model model){
        String tpassword = userService.verifyPasswordByUsername(username);
        if (tpassword.equals(password)){
            User user = userService.findUserByUsername(username);
            session.setAttribute("uid",user.getUid());
            session.setAttribute("username",user.getUsername());
            session.setAttribute("nickname",user.getNickname());
            session.setAttribute("user",user);

            return "redirect:/index.html";
        }else{
            model.addAttribute("msg","用户名或密码错误");
            return "user/login";
        }
    }
    //注销
    @RequestMapping("/cancellation")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/index.html";
    }
    //注册(添加用户)
    @RequestMapping("/register")
    public String register(User user,Model model){
        boolean isExsit = userService.isExsit(user.getUsername());
        if (isExsit){
            model.addAttribute("msg","用户名已存在");
            return "user/register";
        }else{
            userService.register(user);
            return "user/success";
        }
    }
    //根据用户id查询用户信息
    @RequestMapping("/findUserById/{uid}")
    public String findUserById(@PathVariable String uid,Model model,HttpSession session){
        session.setAttribute("uidfw",uid);
        User user = userService.findUserById(uid);
        model.addAttribute("user",user);
        List<Integer> allZan = userService.getUpZanByid(user.getUid());
        List<Integer> allBo = userService.getUpBoByid(user.getUid());
        int countZan = 0;
        int countBo = 0;
        for (int o : allZan) {
            countZan = countZan + o;
        }
        for (Integer integer : allBo) {
            countBo = countBo + integer;
        }
        model.addAttribute("allZan",countZan);
        model.addAttribute("allBo",countBo);
        model.addAttribute("sit",1);
        return "/space";
    }
    //根据用户id查询用户信息(去收藏)
    @RequestMapping("/findUserById2/{uid}")
    public String findUserById2(@PathVariable String uid,Model model,HttpSession session){
        session.setAttribute("uidfw",uid);
        User user = userService.findUserById(uid);
        model.addAttribute("user",user);
        List<Integer> allZan = userService.getUpZanByid(user.getUid());
        List<Integer> allBo = userService.getUpBoByid(user.getUid());
        int countZan = 0;
        int countBo = 0;
        for (int o : allZan) {
            countZan = countZan + o;
        }
        for (Integer integer : allBo) {
            countBo = countBo + integer;
        }
        model.addAttribute("allZan",countZan);
        model.addAttribute("allBo",countBo);
        model.addAttribute("sit",2);
        return "/space";
    }
    //个人空间-全部关注(含分页)
    @RequestMapping("/findAllFocus/{upid}")
    public String findAllFocus(HttpServletRequest req, Model model, HttpSession session,
                               @PathVariable int upid){
        Page page = new Page();
        Map map = commomSet(req,upid,page);
        String uid = session.getAttribute("uid").toString();
        map.put("uid",uid);
        List<User> allFocus = userService.findAllFocus(map);
        for (User focus : allFocus) {
            String upids = focus.getUid();
            map.put("upid",upids);
            boolean isFans = userService.isFans(map);
            focus.setTemp(isFans);
        }
        //page赋值
        page.setBeanList(allFocus);
        model.addAttribute("page",page);
        return "navigation/follow";
    }
    //个人空间-全部粉丝(含分页)
    @RequestMapping("/findAllFans/{upid}")
    public String findAllFans(HttpServletRequest req, Model model, HttpSession session,
                               @PathVariable int upid){
        Page page = new Page();
        Map map = commomSet(req,upid,page);
        String uid = session.getAttribute("uid").toString();
        map.put("uid",uid);
        List<User> allFocus = userService.findAllFans(map);
        for (User focus : allFocus) {
            String upids = focus.getUid();
            map.put("upid",upids);
            boolean isFans = userService.isFans(map);
            focus.setTemp(isFans);
        }
        //page赋值
        page.setBeanList(allFocus);
        model.addAttribute("page",page);
        return "navigation/follow";
    }
    //个人空间-投稿(含分页)
    @RequestMapping("/findAllTouGao/{upid}")
    public String findAllTouGao(HttpServletRequest req, Model model,
                              @PathVariable int upid){
        Page page = new Page();
        Map map = commomSet(req,upid,page);
        List<Video> allTouGao = userService.findAllTouGao(map);
        //page赋值
        page.setBeanList(allTouGao);
        model.addAttribute("page",page);
        return "navigation/contribute";
    }
    //个人空间追番追剧(含分页)
    @RequestMapping("/findAllZhuiFan/{upid}")
    public String findAllZhuiFan(HttpServletRequest req, Model model,
                                @PathVariable int upid){
        Page page = new Page();
        Map map = commomSet(req,upid,page);
        List<Fan> allZhuiFan = userService.findAllZhuiFan(map);
        //page赋值
        page.setBeanList(allZhuiFan);
        model.addAttribute("page",page);
        return "navigation/state";
    }
    //个人空间收藏(含分页)
    @RequestMapping("/findAllCang/{upid}")
    public String findAllCang(HttpServletRequest req, Model model,
                                 @PathVariable int upid){
        Page page = new Page();
        Map map = commomSet(req,upid,page);
        List<Video> allCang = userService.findAllCang(map);
        //page赋值
        page.setBeanList(allCang);
        model.addAttribute("page",page);
        return "navigation/collect";
    }
    //查询当前用户的历史记录
    @RequestMapping("/findAllHisByUid/{uid}")
    public String findAllHisByUid(@PathVariable String uid,Model model){
        List<History> allHis = userService.findAllHisByUid(uid);
        model.addAttribute("allHis",allHis);
        return "history";
    }
    //删除
    @RequestMapping("/deleteHis/{vid}")
    public String deleteHis(@PathVariable String vid,Model model,HttpSession session){
        String uid = session.getAttribute("uid").toString();
        Map map = new HashMap();
        map.put("uid",uid);
        map.put("vid",vid);
        userService.deleteHis(map);
        return findAllHisByUid(uid,model);
    }
    //批量删除
    @RequestMapping("/deleteManyHis")
    public String deleteManyHis(Model model,HttpSession session){
        String uid = session.getAttribute("uid").toString();
        userService.deleteManyHis(uid);
        return findAllHisByUid(uid,model);
    }
    //关注
    @RequestMapping("/focusUp/{upid}")
    public String focusUp(@PathVariable String upid,Model model,HttpSession session){
        String uidfw = session.getAttribute("uidfw").toString();
        String fansid = session.getAttribute("uid").toString();
        Map map = new HashMap();
        map.put("upid",upid);
        map.put("fansid",fansid);
        userService.focusUp(map);
        userService.updateUp(upid);
        userService.updateUp2(fansid);
        return findUserById(uidfw,model,session);
    }
    //取消关注
    @RequestMapping("/cancelFocus/{upid}")
    public String cancelFocus(@PathVariable String upid,Model model,HttpSession session){
        String uidfw = session.getAttribute("uidfw").toString();
        String fansid = session.getAttribute("uid").toString();
        Map map = new HashMap();
        map.put("upid",upid);
        map.put("fansid",fansid);
        userService.cancelFocus(map);
        userService.cancelUp(upid);
        userService.cancelUp2(fansid);
        return findUserById(uidfw,model,session);
    }
    //抽取共同部分
    private synchronized Map commomSet(HttpServletRequest req,int upid,Page page){
        int pc = getPc(req);
        String url = getUrl(req);
        //查找数量(总共条目数)
        int tr;
        if (url.contains("findAllFocus")){
            tr = userService.getNumber(upid);
        }else if(url.contains("findAllFans")){
            tr = userService.getNumber2(upid);
        }else if(url.contains("findAllTouGao")){
            tr = userService.getNumber3(upid);
        }else if(url.contains("findAllZhuiFan")){
            tr = userService.getNumber4(upid);
        }else{
            tr = userService.getNumber5(upid);
        }
        //每页数量
        int ps = PageConstants.User_Page_Size;
        //查找指定页的所有番剧
        Map map = new HashMap();
        map.put("start",(pc-1)*ps);
        map.put("end",ps);
        map.put("upid",upid);
        //赋值
        page.setTr(tr);//总共条目数
        page.setPs(ps);//每页条目数
        page.setPc(pc);//设置当前页
        page.setUrl(url);//路径
        return map;
    }
    //获取当前页码
    private int getPc(HttpServletRequest req) {
        int pc = 1;/*初始化为第1页*/
        String param = req.getParameter("pc");
        if(param!=null&&!param.trim().isEmpty()) {
            try {
                pc = Integer.parseInt(param);//假设添加"ABC",报异常不处理，赋值失败，pc = 1
            }catch(RuntimeException e){}
        }
        return pc;
    }
    /* 获得url
     * http://localhost:8080/goods/BookServlet?method=findByBname&&bname=xxx请求网址
     * /goods/BookSevlet + method=findByBname&&bname=xxx*/
    private String getUrl(HttpServletRequest req) {
        String url;

        if (req.getQueryString()==null){
            url = req.getRequestURI()+"?";
        }else{
            url = req.getRequestURI()+"?"+req.getQueryString();
        }
        //+req.getQueryString();
        /*
         * 如果url中存在pc参数，截取掉，如果不存在那就不用截取
         */
        int index = url.lastIndexOf("&pc=");
        if(index!=-1) {
            url = url.substring(0,index);
        }
        return url;
    }

}
